import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Upload, message, Switch, InputNumber, Button, Space } from 'antd';
import { UploadOutlined, SoundOutlined } from '@ant-design/icons';
import { createDetectionText, updateDetectionText, generatePinyin } from '@/services/learningContentApi';
import { uploadAudio } from '@/services/systemManagementApi';

interface DetectionTextFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: LEARNING.DetectionTextModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const DetectionTextForm: React.FC<DetectionTextFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [audioUrl, setAudioUrl] = useState<string>('');
  const [pinyinGenerating, setPinyinGenerating] = useState(false);

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialValues) {
        form.setFieldsValue(initialValues);
        setAudioUrl(initialValues.audio_url || '');
      } else {
        form.resetFields();
        setAudioUrl('');
      }
    }
  }, [visible, mode, initialValues, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        audio_url: audioUrl,
      };

      if (mode === 'create') {
        await createDetectionText(submitData);
        message.success('检测文本创建成功');
      } else {
        await updateDetectionText(initialValues!.id, submitData);
        message.success('检测文本更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '检测文本创建失败' : '检测文本更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理音频上传
  const handleAudioUpload = async (file: File) => {
    try {
      const response = await uploadAudio(file);
      setAudioUrl(response.data.url);
      message.success('音频上传成功');
      return false;
    } catch (error) {
      message.error('音频上传失败');
      return false;
    }
  };

  // 处理生成拼音
  const handleGeneratePinyin = async () => {
    const content = form.getFieldValue('content');
    if (!content) {
      message.warning('请先输入文本内容');
      return;
    }

    setPinyinGenerating(true);
    try {
      // 这里应该调用拼音生成API
      const response = await fetch('/api/generate-pinyin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: content }),
      });
      const data = await response.json();
      
      if (data.success) {
        form.setFieldsValue({ pinyin: data.pinyin });
        message.success('拼音生成成功');
      } else {
        message.error('拼音生成失败');
      }
    } catch (error) {
      message.error('拼音生成失败');
    } finally {
      setPinyinGenerating(false);
    }
  };

  return (
    <Modal
      title={mode === 'create' ? '新建检测文本' : '编辑检测文本'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={700}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          difficulty: 'medium',
          category: 'daily',
          status: 'active',
          is_featured: false,
          sort_order: 0,
        }}
      >
        <Form.Item
          name="content"
          label="文本内容"
          rules={[
            { required: true, message: '请输入文本内容' },
            { max: 500, message: '文本内容不能超过500个字符' },
          ]}
        >
          <Input.TextArea
            rows={4}
            placeholder="请输入检测文本内容"
            showCount
            maxLength={500}
          />
        </Form.Item>

        <Form.Item
          name="pinyin"
          label="拼音标注"
        >
          <Space.Compact style={{ width: '100%' }}>
            <Input
              style={{ width: 'calc(100% - 100px)' }}
              placeholder="请输入拼音标注或点击生成"
            />
            <Button
              type="primary"
              loading={pinyinGenerating}
              onClick={handleGeneratePinyin}
              icon={<SoundOutlined />}
            >
              生成拼音
            </Button>
          </Space.Compact>
        </Form.Item>

        <Form.Item
          name="difficulty"
          label="难度等级"
          rules={[{ required: true, message: '请选择难度等级' }]}
        >
          <Select placeholder="请选择难度等级">
            <Select.Option value="easy">简单</Select.Option>
            <Select.Option value="medium">中等</Select.Option>
            <Select.Option value="hard">困难</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="category"
          label="文本分类"
          rules={[{ required: true, message: '请选择文本分类' }]}
        >
          <Select placeholder="请选择文本分类">
            <Select.Option value="daily">日常用语</Select.Option>
            <Select.Option value="business">商务用语</Select.Option>
            <Select.Option value="academic">学术用语</Select.Option>
            <Select.Option value="poetry">诗词歌赋</Select.Option>
            <Select.Option value="idiom">成语俗语</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="音频文件"
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {audioUrl && (
              <audio controls style={{ maxWidth: 300 }}>
                <source src={audioUrl} type="audio/mpeg" />
                您的浏览器不支持音频播放
              </audio>
            )}
            <Upload
              showUploadList={false}
              beforeUpload={handleAudioUpload}
              accept="audio/*"
            >
              <Button icon={<UploadOutlined />}>
                {audioUrl ? '重新上传' : '上传音频'}
              </Button>
            </Upload>
          </div>
          <div style={{ fontSize: '12px', color: '#666', marginTop: 8 }}>
            支持 MP3、WAV 格式，文件大小不超过 10MB
          </div>
        </Form.Item>

        <Form.Item
          name="description"
          label="文本描述"
        >
          <Input.TextArea
            rows={3}
            placeholder="请输入文本描述或使用说明"
            showCount
            maxLength={200}
          />
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
        >
          <Select
            mode="tags"
            placeholder="请输入标签，用于分类和搜索"
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item
          name="sort_order"
          label="排序权重"
        >
          <InputNumber
            style={{ width: '100%' }}
            placeholder="请输入排序权重，数字越小越靠前"
            min={0}
          />
        </Form.Item>

        <Form.Item
          name="is_featured"
          label="是否推荐"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Select.Option value="active">启用</Select.Option>
            <Select.Option value="inactive">禁用</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="source"
          label="文本来源"
        >
          <Input placeholder="请输入文本来源，如：教材、网络、自创等" />
        </Form.Item>

        <Form.Item
          name="author"
          label="作者"
        >
          <Input placeholder="请输入作者姓名" />
        </Form.Item>

        <Form.Item
          name="reference_url"
          label="参考链接"
          rules={[
            { type: 'url', message: '请输入有效的URL地址' },
          ]}
        >
          <Input placeholder="请输入参考链接" />
        </Form.Item>

        <Form.Item
          name="notes"
          label="备注"
        >
          <Input.TextArea
            rows={2}
            placeholder="请输入备注信息"
            showCount
            maxLength={100}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default DetectionTextForm;
